package com.coursehub.progress.controller;

import com.coursehub.progress.dto.ChapterProgressUpdateDto;
import com.coursehub.progress.dto.MaterialProgressUpdateDto;
import com.coursehub.progress.dto.ProgressResponseDto;
import com.coursehub.progress.entity.StudentChapter;
import com.coursehub.progress.entity.StudentMaterial;
import com.coursehub.progress.service.ProgressService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

/**
 * 学习进度控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/progress")
@RequiredArgsConstructor
@Validated
public class ProgressController {
    
    private final ProgressService progressService;
    
    /**
     * 更新章节学习进度
     */
    @PostMapping("/chapters")
    public ResponseEntity<StudentChapter> updateChapterProgress(@Valid @RequestBody ChapterProgressUpdateDto dto) {
        log.info("更新章节学习进度: userId={}, chapterId={}, isFinished={}", 
                dto.getUserId(), dto.getChapterId(), dto.getIsFinished());
        
        StudentChapter result = progressService.updateChapterProgress(dto);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 更新资料学习进度
     */
    @PostMapping("/materials")
    public ResponseEntity<StudentMaterial> updateMaterialProgress(@Valid @RequestBody MaterialProgressUpdateDto dto) {
        log.info("更新资料学习进度: userId={}, materialId={}, isFinished={}", 
                dto.getUserId(), dto.getMaterialId(), dto.getIsFinished());
        
        StudentMaterial result = progressService.updateMaterialProgress(dto);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取用户在指定课程的章节学习进度
     */
    @GetMapping("/chapters/user/{userId}/course/{courseId}")
    public ResponseEntity<List<StudentChapter>> getUserChapterProgress(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String courseId) {
        
        log.info("获取用户章节学习进度: userId={}, courseId={}", userId, courseId);
        
        List<StudentChapter> progress = progressService.getUserChapterProgress(userId, courseId);
        return ResponseEntity.ok(progress);
    }
    
    /**
     * 获取用户在指定课程的资料学习进度
     */
    @GetMapping("/materials/user/{userId}/course/{courseId}")
    public ResponseEntity<List<StudentMaterial>> getUserMaterialProgress(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String courseId) {
        
        log.info("获取用户资料学习进度: userId={}, courseId={}", userId, courseId);
        
        List<StudentMaterial> progress = progressService.getUserMaterialProgress(userId, courseId);
        return ResponseEntity.ok(progress);
    }
    
    /**
     * 获取用户在指定课程的整体学习进度
     */
    @GetMapping("/overall/user/{userId}/course/{courseId}")
    public ResponseEntity<ProgressResponseDto> getUserOverallProgress(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String courseId) {
        
        log.info("获取用户整体学习进度: userId={}, courseId={}", userId, courseId);
        
        ProgressResponseDto progress = progressService.getUserOverallProgress(userId, courseId);
        return ResponseEntity.ok(progress);
    }
    
    /**
     * 获取课程学习进度百分比
     */
    @GetMapping("/courses/{courseId}/user/{userId}/percentage")
    public ResponseEntity<Integer> getCourseProgress(
            @PathVariable @NotBlank String courseId,
            @PathVariable @NotBlank String userId) {
        
        log.info("获取课程学习进度百分比: userId={}, courseId={}", userId, courseId);
        
        Integer progress = progressService.getCourseProgress(userId, courseId);
        return ResponseEntity.ok(progress);
    }
    
    /**
     * 获取章节学习进度百分比
     */
    @GetMapping("/chapters/{chapterId}/user/{userId}/percentage")
    public ResponseEntity<Integer> getChapterProgress(
            @PathVariable @NotBlank String chapterId,
            @PathVariable @NotBlank String userId) {
        
        log.info("获取章节学习进度百分比: userId={}, chapterId={}", userId, chapterId);
        
        Integer progress = progressService.getChapterProgress(userId, chapterId);
        return ResponseEntity.ok(progress);
    }
    
    /**
     * 获取资料学习进度百分比
     */
    @GetMapping("/materials/{materialId}/user/{userId}/percentage")
    public ResponseEntity<Integer> getMaterialProgress(
            @PathVariable @NotBlank String materialId,
            @PathVariable @NotBlank String userId) {
        
        log.info("获取资料学习进度百分比: userId={}, materialId={}", userId, materialId);
        
        Integer progress = progressService.getMaterialProgress(userId, materialId);
        return ResponseEntity.ok(progress);
    }
    
    /**
     * 批量获取章节学习进度
     */
    @PostMapping("/chapters/batch/user/{userId}")
    public ResponseEntity<Map<String, Integer>> getBatchChapterProgress(
            @PathVariable @NotBlank String userId,
            @RequestBody List<String> chapterIds) {
        
        log.info("批量获取章节学习进度: userId={}, chapterIds={}", userId, chapterIds);
        
        Map<String, Integer> progress = progressService.getBatchChapterProgress(userId, chapterIds);
        return ResponseEntity.ok(progress);
    }
    
    /**
     * 批量获取资料学习进度
     */
    @PostMapping("/materials/batch/user/{userId}")
    public ResponseEntity<Map<String, Boolean>> getBatchMaterialProgress(
            @PathVariable @NotBlank String userId,
            @RequestBody List<String> materialIds) {
        
        log.info("批量获取资料学习进度: userId={}, materialIds={}", userId, materialIds);
        
        Map<String, Boolean> progress = progressService.getBatchMaterialProgress(userId, materialIds);
        return ResponseEntity.ok(progress);
    }
    
    /**
     * 获取班级课程完成率统计
     */
    @GetMapping("/statistics/class/{classId}/completion-rate")
    public ResponseEntity<Integer> getClassCompletionRate(@PathVariable @NotBlank String classId) {
        log.info("获取班级课程完成率: classId={}", classId);
        
        Integer completionRate = progressService.getClassCompletionRate(classId);
        return ResponseEntity.ok(completionRate);
    }
    
    /**
     * 获取练习完成率统计
     */
    @GetMapping("/statistics/exercise/{exerciseId}/completion-rate")
    public ResponseEntity<Integer> getExerciseCompletionRate(@PathVariable @NotBlank String exerciseId) {
        log.info("获取练习完成率: exerciseId={}", exerciseId);
        
        Integer completionRate = progressService.getExerciseCompletionRate(exerciseId);
        return ResponseEntity.ok(completionRate);
    }
    
    /**
     * 验证用户是否存在
     */
    @GetMapping("/validate/user/{userId}")
    public ResponseEntity<Boolean> validateUser(@PathVariable @NotBlank String userId) {
        boolean exists = progressService.validateUser(userId);
        return ResponseEntity.ok(exists);
    }
    
    /**
     * 验证课程是否存在
     */
    @GetMapping("/validate/course/{courseId}")
    public ResponseEntity<Boolean> validateCourse(@PathVariable @NotBlank String courseId) {
        boolean exists = progressService.validateCourse(courseId);
        return ResponseEntity.ok(exists);
    }
    
    /**
     * 验证章节是否存在
     */
    @GetMapping("/validate/chapter/{chapterId}")
    public ResponseEntity<Boolean> validateChapter(@PathVariable @NotBlank String chapterId) {
        boolean exists = progressService.validateChapter(chapterId);
        return ResponseEntity.ok(exists);
    }
    
    /**
     * 验证资料是否存在
     */
    @GetMapping("/validate/material/{materialId}")
    public ResponseEntity<Boolean> validateMaterial(@PathVariable @NotBlank String materialId) {
        boolean exists = progressService.validateMaterial(materialId);
        return ResponseEntity.ok(exists);
    }
    
    /**
     * 验证班级是否存在
     */
    @GetMapping("/validate/class/{classId}")
    public ResponseEntity<Boolean> validateClass(@PathVariable @NotBlank String classId) {
        boolean exists = progressService.validateClass(classId);
        return ResponseEntity.ok(exists);
    }
    
    /**
     * 验证练习是否存在
     */
    @GetMapping("/validate/exercise/{exerciseId}")
    public ResponseEntity<Boolean> validateExercise(@PathVariable @NotBlank String exerciseId) {
        boolean exists = progressService.validateExercise(exerciseId);
        return ResponseEntity.ok(exists);
    }
    
    // ====================== 资料学习状态管理API（兼容单体系统） ======================
    
    /**
     * 获取学生在指定章节中已完成的资料
     * 兼容单体系统API: GET /api/materials/student/{userId}/chapter/{chapterId}/completed
     */
    @GetMapping("/materials/student/{userId}/chapter/{chapterId}/completed")
    public ResponseEntity<List<Map<String, Object>>> getCompletedMaterialsByStudentAndChapter(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String chapterId) {
        
        log.info("获取学生已完成资料: userId={}, chapterId={}", userId, chapterId);
        
        List<Map<String, Object>> materials = progressService.getCompletedMaterialsByStudentAndChapter(userId, chapterId);
        return ResponseEntity.ok(materials);
    }
    
    /**
     * 更新学生资料学习状态
     * 兼容单体系统API: PUT /api/materials/student/status
     */
    @PutMapping("/materials/student/status")
    public ResponseEntity<String> updateMaterialStatus(
            @RequestParam("userId") @NotBlank String userId,
            @RequestParam("materialId") @NotBlank String materialId,
            @RequestParam("isFinished") boolean isFinished) {
        
        log.info("更新学生资料学习状态: userId={}, materialId={}, isFinished={}", userId, materialId, isFinished);
        
        progressService.updateStudentMaterialStatus(userId, materialId, isFinished);
        return ResponseEntity.ok("学习状态更新成功");
    }
    
    /**
     * 获取学生学习资料状态
     * 兼容单体系统API: GET /api/materials/student/status
     */
    @GetMapping("/materials/student/status")
    public ResponseEntity<Boolean> getMaterialStatus(
            @RequestParam("userId") @NotBlank String userId,
            @RequestParam("materialId") @NotBlank String materialId) {
        
        log.info("获取学生资料学习状态: userId={}, materialId={}", userId, materialId);
        
        boolean isFinished = progressService.getStudentMaterialStatus(userId, materialId);
        return ResponseEntity.ok(isFinished);
    }
    
    /**
     * 获取学生已完成的章节ID列表
     * 支持课程管理服务调用: GET /api/progress/chapter/user/{userId}/course/{courseId}/completed
     */
    @GetMapping("/chapter/user/{userId}/course/{courseId}/completed")
    public ResponseEntity<List<String>> getCompletedChapterIds(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String courseId) {
        log.info("获取已完成章节ID列表: userId={}, courseId={}", userId, courseId);
        List<String> completedChapterIds = progressService.getCompletedChapterIds(userId, courseId);
        return ResponseEntity.ok(completedChapterIds);
    }
    
    /**
     * 获取学生已完成的资料ID列表
     * 支持课程管理服务调用: GET /api/progress/material/user/{userId}/course/{courseId}/completed
     */
    @GetMapping("/material/user/{userId}/course/{courseId}/completed")
    public ResponseEntity<List<String>> getCompletedMaterialIds(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String courseId) {
        log.info("获取已完成资料ID列表: userId={}, courseId={}", userId, courseId);
        List<String> completedMaterialIds = progressService.getCompletedMaterialIds(userId, courseId);
        return ResponseEntity.ok(completedMaterialIds);
    }
    
    /**
     * 标记章节为完成状态
     * 支持课程管理服务调用: POST /api/progress/chapter/user/{userId}/chapter/{chapterId}/complete
     */
    @PostMapping("/chapter/user/{userId}/chapter/{chapterId}/complete")
    public ResponseEntity<Void> markChapterAsComplete(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String chapterId) {
        log.info("标记章节完成: userId={}, chapterId={}", userId, chapterId);
        progressService.markChapterAsComplete(userId, chapterId);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 标记资料为完成状态
     * 支持课程管理服务调用: POST /api/progress/material/user/{userId}/material/{materialId}/complete
     */
    @PostMapping("/material/user/{userId}/material/{materialId}/complete")
    public ResponseEntity<Void> markMaterialAsComplete(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String materialId) {
        log.info("标记资料完成: userId={}, materialId={}", userId, materialId);
        progressService.markMaterialAsComplete(userId, materialId);
        return ResponseEntity.ok().build();
    }
    
    // ==================== 练习完成状态管理API ====================
    
    /**
     * 获取用户已完成的练习列表
     */
    @GetMapping("/exercise/user/{userId}/completed")
    public ResponseEntity<List<String>> getCompletedExerciseIds(@PathVariable @NotBlank String userId) {
        log.info("获取用户已完成的练习列表: userId={}", userId);
        List<String> completedExerciseIds = progressService.getCompletedExerciseIds(userId);
        return ResponseEntity.ok(completedExerciseIds);
    }
    
    /**
     * 获取用户未完成的练习列表
     */
    @GetMapping("/exercise/user/{userId}/unfinished")
    public ResponseEntity<List<String>> getUnfinishedExerciseIds(@PathVariable @NotBlank String userId) {
        log.info("获取用户未完成的练习列表: userId={}", userId);
        List<String> unfinishedExerciseIds = progressService.getUnfinishedExerciseIds(userId);
        return ResponseEntity.ok(unfinishedExerciseIds);
    }
    
    /**
     * 根据课程ID获取用户已完成的练习
     */
    @GetMapping("/exercise/user/{userId}/course/{courseId}/completed")
    public ResponseEntity<List<String>> getCompletedExerciseIdsByCourse(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String courseId) {
        log.info("根据课程ID获取用户已完成的练习: userId={}, courseId={}", userId, courseId);
        List<String> completedExerciseIds = progressService.getCompletedExerciseIdsByCourse(userId, courseId);
        return ResponseEntity.ok(completedExerciseIds);
    }
    
    /**
     * 根据课程ID获取用户未完成的练习
     */
    @GetMapping("/exercise/user/{userId}/course/{courseId}/unfinished")
    public ResponseEntity<List<String>> getUnfinishedExerciseIdsByCourse(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String courseId) {
        log.info("根据课程ID获取用户未完成的练习: userId={}, courseId={}", userId, courseId);
        List<String> unfinishedExerciseIds = progressService.getUnfinishedExerciseIdsByCourse(userId, courseId);
        return ResponseEntity.ok(unfinishedExerciseIds);
    }
    
    /**
     * 标记练习为已完成
     */
    @PostMapping("/exercise/user/{userId}/exercise/{exerciseId}/complete")
    public ResponseEntity<Void> markExerciseAsComplete(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String exerciseId,
            @RequestParam(value = "score", required = false) Integer score) {
        log.info("标记练习为已完成: userId={}, exerciseId={}, score={}", userId, exerciseId, score);
        progressService.markExerciseAsComplete(userId, exerciseId, score);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 检查用户是否完成了指定练习
     */
    @GetMapping("/exercise/user/{userId}/exercise/{exerciseId}/completed")
    public ResponseEntity<Boolean> isExerciseCompleted(
            @PathVariable @NotBlank String userId,
            @PathVariable @NotBlank String exerciseId) {
        boolean isCompleted = progressService.isExerciseCompleted(userId, exerciseId);
        return ResponseEntity.ok(isCompleted);
    }
    
    /**
     * 获取用户练习完成状态
     */
    @GetMapping("/exercise/student/status")
    public ResponseEntity<Boolean> getExerciseStatus(
            @RequestParam("userId") @NotBlank String userId,
            @RequestParam("exerciseId") @NotBlank String exerciseId) {
        log.info("获取用户练习完成状态: userId={}, exerciseId={}", userId, exerciseId);
        boolean status = progressService.getStudentExerciseStatus(userId, exerciseId);
        return ResponseEntity.ok(status);
    }
    
    /**
     * 更新学生练习状态
     */
    @PutMapping("/exercise/student/status")
    public ResponseEntity<String> updateExerciseStatus(
            @RequestParam("userId") @NotBlank String userId,
            @RequestParam("exerciseId") @NotBlank String exerciseId,
            @RequestParam("isFinished") boolean isFinished,
            @RequestParam(value = "score", required = false) Integer score) {
        log.info("更新学生练习状态: userId={}, exerciseId={}, isFinished={}, score={}", userId, exerciseId, isFinished, score);
        progressService.updateStudentExerciseStatus(userId, exerciseId, isFinished, score);
        return ResponseEntity.ok("练习状态更新成功");
    }
    
    /**
     * 创建学习进度记录（用于选课事务）
     */
    @PostMapping
    public ResponseEntity<String> createProgressRecord(@RequestBody Map<String, Object> progressData) {
        log.info("创建学习进度记录: {}", progressData);
        
        String studentId = (String) progressData.get("studentId");
        String courseId = (String) progressData.get("courseId");
        
        if (studentId == null || courseId == null) {
            return ResponseEntity.badRequest().body("studentId和courseId不能为空");
        }
        
        try {
            // 验证用户和课程是否存在
            if (!progressService.validateUser(studentId)) {
                return ResponseEntity.badRequest().body("用户不存在: " + studentId);
            }
            if (!progressService.validateCourse(courseId)) {
                return ResponseEntity.badRequest().body("课程不存在: " + courseId);
            }
            
            // 创建学习进度记录的逻辑已经通过现有的API实现
            // 这里只需要返回成功响应，实际的进度记录会在学生开始学习时创建
            String progressId = "progress_" + studentId + "_" + courseId + "_" + System.currentTimeMillis();
            
            log.info("成功创建学习进度记录: studentId={}, courseId={}, progressId={}", studentId, courseId, progressId);
            return ResponseEntity.ok(progressId);
            
        } catch (Exception e) {
            log.error("创建学习进度记录失败: studentId={}, courseId={}, 错误: {}", studentId, courseId, e.getMessage(), e);
            return ResponseEntity.status(500).body("创建学习进度记录失败: " + e.getMessage());
        }
    }
}